﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CognisessService;
using CognisessDA;
using CognisessCommLib;
using CognisessWeb.Models;
using System.Xml;
using System.Xml.Linq;

namespace CognisessWeb.Controllers
{
    public class AccountController : Controller
    {
        AccountBLL accountBLL = new AccountBLL();

        #region Create by lixiaodong
        [HttpPost]
        public ActionResult AddUser()
        {
            CognisessDA.User user = new User();

            user.Username = Request.Form["newUserName"].ToString().Trim();
            user.Password = Request.Form["emailAddress"].ToString().Trim();
            user.Email = Request.Form["newPassWord"].ToString().Trim();

            accountBLL.AddUser(new List<User> { user });
            return View();
        }

        public ActionResult Login()
        {
            return View();
        }

        #region Login and logout
        [HttpPost]
        public ActionResult Login(string userName, string passWord)
        {
            CognisessDA.User queryCondition = new User();
            queryCondition.Username = userName;
            queryCondition.Password = passWord;
            List<User> result = accountBLL.GetUser(queryCondition);
            if (result.Count == 0)
            {
                // pop message "user or password"
                ViewData["LoginInfo"] = "Invalid user/password combination ";
                return View();
            }
            else if (result.Count == 1)
            {
                Session["User"] = result.First();
                ViewData["LoginInfo"] = null;
                // go to login successfull page.
                return RedirectToAction("Index", "Home");
            }
            else
            {
                ViewData["LoginInfo"] = "System error. Please contact with Cognisess ";
                // go to error page.
                return View();
            }
        }

        public ActionResult Logout()
        {
            Session["User"] = null;
            return View();
        }
        #endregion
        #endregion

        #region Create by wanglongxiang
        public ActionResult Why()
        {
            return View();
        }

        public ActionResult Science()
        {
            return View();
        }

        public ActionResult About_us()
        {
            return View();
        }

        public ActionResult Media()
        {
            return View();
        }

        public ActionResult More()
        {
            return View();
        }

        public ActionResult Product()
        {
            return View();
        }

        public ActionResult Brain()
        {
            return View();
        }

        public ActionResult Health()
        {
            return View();
        }

        public ActionResult Neuroscience()
        {
            return View();
        }

        public ActionResult Results()
        {
            return View();
        }

        public ActionResult Training_cognitive_skills()
        {
            return View();
        }

        public ActionResult StartCognidrive()
        {
            return View();
        }

        public ActionResult YourProduct()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Review()
        {
            return View();
        }

        public ActionResult Personalise()
        {
            ViewData["Education"] = new SelectList(XMLHelper.GetOptions("Education"), "Value", "Text", 0);
            ViewData["TimeZoneT"] = new SelectList(XMLHelper.GetOptions("TimeZone"), "Value", "Text", 0);
            ViewData["About"] = new SelectList(XMLHelper.GetOptions("About"), "Value", "Text", 0);
            return View();
        }

        public ActionResult Sign_up()
        {
            return View();
        }

        [LoginFilter]
        public ActionResult AccountSettings(string newUsername, string emailAddress)
        {
            string errorMsg = string.Empty;
            bool isSuccessfull = false;
            #region Check the user name and email whether exist in the database
            if (newUsername == null || emailAddress == null)
            {
                return View();
            }
            if (accountBLL.GetUser(new User { Username = newUsername }).Count > 0)
            {
                errorMsg = ConstantHelper.ERROR_USER_EXIST;
            }
            if (accountBLL.GetUser(new User { Email = emailAddress }).Count > 0)
            {
                errorMsg = ConstantHelper.ERROR_EMAIL_EXIST;
            }
            #endregion

            if (errorMsg == string.Empty)
            {
                CognisessDA.User oldUser = Session["User"] as CognisessDA.User;
                oldUser.Username = newUsername;
                oldUser.Email = emailAddress;
                isSuccessfull = accountBLL.UpdataUser(new List<User> { oldUser });
            }
            
            if (isSuccessfull)
            {
                return View();
            }
            else
            {
                Response.Write("<script>alert('" + errorMsg + "');history.back(-1);</script>");
                return View();
            }
        }

        [HttpPost]
        public ActionResult CognisessExperience(User user)
        {
            bool isSuccessfull = false;
            User u = Session["User"] as CognisessDA.User;
            u.Firstname = user.Firstname;
            u.EducationLevel = user.EducationLevel;
            u.TimeZone = user.TimeZone;
            string date = Request.Form["sltYear"].ToString();
            date += "-" + Request.Form["sltMonth"].ToString();
            date += "-" + Request.Form["sltDay"].ToString();
            u.BirthDate = DateTime.Parse(date);
            u.Gender = user.Gender;
            user.HowToKnowUs = user.HowToKnowUs;
            isSuccessfull = accountBLL.UpdataUser(new List<User> { u });
            if (isSuccessfull)
            {
                return View();
            }
            else
            {
                Response.Write("<script>alert('Modify failure!');</script>");
                return View();
            }
        }

        [HttpPost]
        public ActionResult Next(string newUserName, string emailAddress, string newPassWord)
        {
            #region Modify by lixiaodong 20110419

            string errorMsg = string.Empty;
            bool isSuccessfull = false;
            #region Check the user name and email whether exist in the database
            if (accountBLL.GetUser(new User { Username = newUserName }).Count > 0)
            {
                errorMsg = ConstantHelper.ERROR_USER_EXIST;
            }
            if (accountBLL.GetUser(new User { Email = emailAddress }).Count > 0)
            {
                errorMsg = ConstantHelper.ERROR_EMAIL_EXIST;
            }
            #endregion

            if (errorMsg == string.Empty)
            {
                isSuccessfull = accountBLL.AddUser(new List<User> { new User { Username = newUserName, Password = newPassWord, Email = emailAddress,CreateTime = DateTime.Now } });  
            }

            if (isSuccessfull)
            {
                CognisessDA.User user = new User();
                user.Username = newUserName;
                Session["User"] = accountBLL.GetUser(user).First();
                // 转向下一步页面
                return View();
            }
            else
            {
                // 弹出错误信息并保持当前的页面不变
                Response.Write("<script>alert('" + errorMsg + "');history.back(-1);</script>");
                return View();
            }
            #endregion
            //CognisessDA.User user = new User();
            //user.Username = Request.Form["newUserName"].ToString();
            //user.Password = Request.Form["newPassWord"].ToString();
            //user.Email = Request.Form["emailAddress"].ToString();

            //if (accountBLL.checkUserExsit(user.Username, user.Email))
            //{
            //    accountBLL.AddUser(new List<User> { user });
            //}
            //else
            //{

            //}

            //return View();
        }

        public ActionResult ContactSupport()
        {
            return View();
        }

        public ActionResult Faqs()
        {
            return View();
        }
        #region FeedBack

        public ActionResult Feedback(Feedback feedBack)
        {
            List<Feedback> feedBacks = new List<Feedback>();
            feedBacks.Add(feedBack);
            accountBLL.AddFeedBack(feedBacks);
            return View();
        }

        #endregion

        public ActionResult Mission()
        {
            return View();
        }

        public ActionResult Cognimap()
        {
            return View();
        }

        public ActionResult Experience()
        {
            return View();
        }

        public ActionResult Cognicoach()
        {
            return View();
        }

        public ActionResult Attention()
        {
            return View();
        }

        public ActionResult Memory()
        {
            return View();
        }

        public ActionResult Cognidrive()
        {
            return View();
        }

        public ActionResult Logical_Processing()
        {
            return View();
        }

        #region News

        

        

        
        public ActionResult LatestNews(int? page)
        {
            List<NewsModel> listNews = new List<NewsModel>();
            List<NewsInfo> news = accountBLL.GetNews(new NewsInfo());
            List<Post> posts = new List<Post>();
            foreach (var item in news)
            {
                NewsModel bindNews = new NewsModel();
                bindNews.Id = item.Id;
                bindNews.NewsName = item.NewsName;
                bindNews.Title = item.Title;
                bindNews.NewsContent = item.NewsContent;
                bindNews.CreateTime = DateTime.Parse(item.CreateTime.ToString());
                bindNews.Posts = new List<PostsModel> { };
                posts = accountBLL.GetPost(new Post { NewsId = bindNews.Id });
                for (int i = 0; i < posts.Count; i++)
                {
                    bindNews.Posts.Add(new PostsModel { NewsId = bindNews.Id, Title = bindNews.Title, Content = posts[i].PostContent, Id = posts[i].Id, DateCreated = DateTime.Parse(posts[i].dateCreated.ToString()) });
                }
                listNews.Add(bindNews);
            }
            if (page == null)
                page = 0;
            const int pageSize = 3;
            var list = listNews.Skip((page ?? 0) * pageSize).Take(pageSize);
            return View(list);
        }
        public ActionResult NewsDetails(int Id)
        {
            List<NewsInfo> news = accountBLL.GetNews(new NewsInfo { Id = Id });
            List<Post> posts = new List<Post>();
            NewsModel bindNews = new NewsModel();
            foreach (var item in news)
            {                
                bindNews.Id = item.Id;
                bindNews.NewsName = item.NewsName;
                bindNews.Title = item.Title;
                bindNews.NewsContent = item.NewsContent;
                bindNews.Posts = new List<PostsModel> { };
                bindNews.CreateTime = DateTime.Parse(item.CreateTime.ToString());
                posts = accountBLL.GetPost(new Post { NewsId = item.Id });
                for (int i = 0; i < posts.Count; i++)
                {
                    bindNews.Posts.Add(new PostsModel { NewsId = bindNews.Id, Title = bindNews.Title, Content = posts[i].PostContent, Id = posts[i].Id, DateCreated = DateTime.Parse(posts[i].dateCreated.ToString()) });
                }
            }
            return View(bindNews);
        }

        #endregion

        #region Blog

        

        public ActionResult Cogniblog(int ? page)
        {
            List<BlogsModel> listBlog = new List<BlogsModel>();
            List<Blog> blogs = accountBLL.GetBlog(new Blog());
            // 每一个view只会绑定一个blog.
            //Blog blog = blogs.FirstOrDefault(); // 需要绑定上去的blog
            List<Post> posts = new List<Post>();
            foreach (var item in blogs)
            {
                BlogsModel bindBlog = new BlogsModel();
                bindBlog.Id = item.Id;
                bindBlog.BloggerName = item.BloggerName;
                bindBlog.Title = item.Title;
                bindBlog.CreateTime = DateTime.Parse(item.CreateTime.ToString());
                bindBlog.Posts = new List<PostsModel> { };
                bindBlog.BlogContent = item.BlogContent;
                posts = accountBLL.GetPost(new Post { BlogId = bindBlog.Id });
                // 根据blog id查询出该blog下面所有的post.
                for (int i = 0; i < posts.Count; i++)
                {
                    List<CommentsModel> commentsModel = new List<CommentsModel>();
                    List<Comment> comments = accountBLL.GetComment(new Comment { PostId = posts[i].Id });
                    // 根据post id查询出每个post下面的comments
                    for (int j = 0; j < comments.Count; j++)
                    {
                        commentsModel.Add(new CommentsModel { Id = comments[j].Id, Content = comments[j].CommentContent, DateCreated = DateTime.Parse(comments[j].DateCreated.ToString()), PostId = posts[i].Id, Post = new PostsModel { Id = posts[i].Id, Title = posts[i].Title, Content = posts[i].PostContent, BlogId = bindBlog.Id, Comments = commentsModel } });
                    }
                    bindBlog.Posts.Add(new PostsModel { BlogId = bindBlog.Id, Content = posts[i].PostContent, Id = posts[i].Id, Title = posts[i].Title, DateCreated = DateTime.Parse(posts[i].dateCreated.ToString()), Comments = commentsModel });
                }
                listBlog.Add(bindBlog);
            }

            if (page == null)
                page = 0;
            const int pageSize = 2;
            var list = listBlog.Skip((page ?? 0) * pageSize).Take(pageSize);
            return View(list); 
        }
        #endregion

        public ActionResult PressReleases()
        {
            return View();
        }

        public ActionResult Twitter()
        {
            return View();
        }

        public ActionResult Library()
        {
            return View();
        }

        public ActionResult Facebook()
        {
            return View();
        }

        public ActionResult Forgot()
        {
            return View();
        }

        public ActionResult Careers()
        {
            return View();
        }

        public ActionResult Application(string Careers,string lastName,string email, string phoneNumber, string city,string country,string coverLetter,string information)
        {
            if (Careers == null || lastName == null || email == null || phoneNumber == null || city == null || country == null || coverLetter == null || information == null) 
            {
                return View();
            }
            CognisessDA.Career career = new Career();
            career.Firstname = Careers;
            career.Lastname = lastName;
            career.Email = email;
            career.Telephone = phoneNumber;
            career.City = city;
            career.Country = country;
            career.AttachLetter = coverLetter;
            career.AddInfor = information;

            accountBLL.AddCareer(new List<Career> { career });
            return View();
        }

        public ActionResult Terms()
        {
            return View();
        }

        public ActionResult RrocePage()
        {
            return View();
        }

        [LoginFilter]
        public ActionResult ChangePassword(string newPassword, string confirmPassword)
        {
            bool isSuccessfull = false;
            if (newPassword == null || confirmPassword == null)
            {
                return View();
            }

            // modify by lixiaodong
            if (Session["User"] != null)
            {
                User oldUser = Session["User"] as CognisessDA.User;
                oldUser.Password = confirmPassword;
                isSuccessfull = accountBLL.UpdataUser(new List<User> { oldUser});
            }
            
            //isSuccessfull = accountBLL.UpdataUser(new List<User> { new User { Username = (Session["User"] as CognisessDA.User).Username, Password = newPassword, Id = (Session["User"] as CognisessDA.User).Id } });
            
            if (isSuccessfull)
            {
                return View();
            }
            
            else
            {
                Response.Write("<script>alert('Modify failure!');history.back(-1);</script>");
                return View();
            }
        }

        public ActionResult Refund()
        {
            return View();
        }

        public ActionResult EmailPreferences()
        {
            return View();
        }

        public ActionResult Games()
        {
            return View();
        }

        public ActionResult NewHtml()
        {
            return View();
        }

        public ActionResult Privacy()
        {
            return View();
        }

        public ActionResult NewHtml_a()
        {
            return View();
        }

        //public ActionResult ViewPage1(int? page)
        //{
        //    //BlogsModel bindBlog = new BlogsModel();
        //    //List<Blog> blogs = accountBLL.GetBlog(new Blog());
        //    //// 每一个view只会绑定一个blog.
        //    //Blog blog = blogs.FirstOrDefault(); // 需要绑定上去的blog
        //    //bindBlog.Id = blog.Id;
        //    //bindBlog.BloggerName = blog.BloggerName;
        //    //bindBlog.Title = blog.Title;
        //    //bindBlog.Posts = new List<PostsModel> {  };
        //    //List<Post> posts = accountBLL.GetPost(new Post {Id = bindBlog.Id }); // 根据blog id查询出该blog下面所有的post.
        //    //for (int i = 0; i < posts.Count; i++)
        //    //{
        //    //    //bindBlog.Posts.Add(new PostsModel { BlogId = bindBlog.Id,  });
        //    //    List<CommentsModel> commentsModel = new List<CommentsModel>();
        //    //    List<Comment> comments = accountBLL.GetComment(new Comment { PostId = posts[i].Id }); // 根据post id查询出每个post下面的comments
        //    //    for (int j = 0; j < comments.Count; j++)
        //    //    {
        //    //        commentsModel.Add(new CommentsModel { Id = comments[j].Id, Content = comments[j].CommentContent, DateCreated = DateTime.Parse(comments[j].DateCreated.ToString()), PostId = posts[j].Id, Post = new PostsModel { Id = posts[j].Id, Title = posts[j].Title, Content = posts[j].PostContent, BlogId = bindBlog.Id, Comments = commentsModel } });
        //    //    }
        //    //    bindBlog.Posts.Add(new PostsModel { BlogId = bindBlog.Id, Content = posts[i].PostContent, Id = posts[i].Id, Title = posts[i].Title, DateCreated = DateTime.Parse(posts[i].dateCreated.ToString()), Comments = commentsModel });
        //    //}
        //    //return View(bindBlog);

            
        //}

        public ActionResult ViewPage1(int? page)
        {
            List<NewsModel> listNews = new List<NewsModel>();
            List<NewsInfo> news = accountBLL.GetNews(new NewsInfo());
            List<Post> posts = new List<Post>();            
            foreach (var item in news)
            {
                NewsModel bindNews = new NewsModel();
                bindNews.Id = item.Id;
                bindNews.NewsName = item.NewsName;
                bindNews.Title = item.Title;
                bindNews.Posts = new List<PostsModel> { };
                posts = accountBLL.GetPost(new Post { NewsId = bindNews.Id });
                for (int i = 0; i < posts.Count; i++)
                {
                    bindNews.Posts.Add(new PostsModel { NewsId = bindNews.Id, Title = bindNews.Title, Content = posts[i].PostContent, Id = posts[i].Id, DateCreated = DateTime.Parse(posts[i].dateCreated.ToString()) });
                }
                listNews.Add(bindNews);
            }
            if (page == null)
                page = 0;
            const int pageSize = 2;
            var list = listNews.Skip((page ?? 0) * pageSize).Take(pageSize);
            return View(list);          
        }

        public IQueryable<Blog> FindUpcomingDinners()
        {
            CognisessDataContext db = new CognisessDataContext();
            return from blog in db.Blog
                   where blog.Id != null
                   orderby blog.Id
                   select blog;
            
        }

        public ActionResult CognitiveProcessing()
        {
            return View();
        }

        public ActionResult TrainingReminders()
        {
            return View();
        }

        public ActionResult Personalisation(User user)
        {
            try
            {
                ViewData["Education"] = new SelectList(XMLHelper.GetOptions("Education"), "Value", "Text", (Session["user"] as CognisessDA.User).EducationLevel);
            ViewData["TimeZoneT"] = new SelectList(XMLHelper.GetOptions("TimeZone"), "Value", "Text", (Session["user"] as CognisessDA.User).TimeZone);
            
            bool isSuccessfull = false;
            User u = Session["User"] as User;
            u.Firstname = user.Firstname;
            u.Gender = user.Gender;
            u.EducationLevel = user.EducationLevel;
            string date = Request.Form["sltYear"].ToString();
            date += "-" + Request.Form["sltMonth"].ToString();
            date += "-" + Request.Form["sltDay"].ToString();
            user.BirthDate = DateTime.Parse(date);
            u.Lastname = user.Lastname;
            u.TimeZone = user.TimeZone;
            u.Id = (Session["User"] as User).Id;


            isSuccessfull = accountBLL.UpdataUser(new List<User> { u });
            if (isSuccessfull)
            {
                return View();
            }
            else
            {
                Response.Write("<script>alert('Modify failure!');history.back(-1);</script>");
                return View();
            }
            }
            catch (Exception)
            {

                return View();
            }
            

        }
        


        public ActionResult SpeedMatch()
        {
            return View();
        }

        public ActionResult TestAB()
        {
            return View();
        }

        [LoginFilter]
        public ActionResult TestFRT()
        {
            return View();
        }

        public ActionResult TestDMT()
        {
            return View();
        }

        public ActionResult TestIMGd()
        {
            return View();
        }

        public ActionResult TestIMGg()
        {
            return View();
        }

        public ActionResult TestMEM()
        {
            return View();
        }

        public ActionResult TestNUM()
        {
            return View();
        }

        public ActionResult TestPAS()
        {
            return View();
        }

        public ActionResult TestPPP()
        {
            return View();
        }

        public ActionResult TestSTR()
        {
            return View();
        }

        public ActionResult Contact_us()
        {
            return View();
        }

        public ActionResult Partnerships()
        {
            return View();
        }


        [ValidateInput(false)]
        [LoginFilter]
        public ActionResult TestPage()
        {            
            try
            {
                List<TestRecord> list = null;
                List<TestRecordModel> trm = new List<TestRecordModel>();
                string s = @Request["xx"].ToString();
                if (s != null)
                    list = GetTestRecords(s);
                if (accountBLL.AddTestRecord(list))
                {
                    list = accountBLL.GetTestRecord(new TestRecord());
                    foreach (var item in list)
                    {
                        TestRecordModel tr = new TestRecordModel();
                        tr.Id = item.Id;
                        tr.UserId = int.Parse(item.UserId.ToString());
                        tr.TestId = int.Parse(item.TestId.ToString());
                        tr.ResponseTime = long.Parse(item.ResponseTime.ToString());
                        tr.Value = item.Value;
                        tr.StepNo = int.Parse(item.StepNo.ToString());
                        tr.TotalTime = int.Parse(item.TotalTime.ToString());
                        trm.Add(tr);
                    }
                    return View(list);
                }
                else
                {
                    Response.Write("<script>alert('Add failure!');</script>");
                    return RedirectToAction("Account", "TestFRT");
                }
            }
            catch (Exception)
            {
                return RedirectToAction("Account", "TestFRT");
            }
            
            
        }

        public static List<TestRecord> GetTestRecords(string @strXML)
        {
//            strXML = @"<data>
//                      <userid>1</userid>
//                      <testid>1</testid>
//                      <infos>
//                        <info isright='true' responsetime='2' bonus='400' totalscore='500'></info>
//                        <info isright='true' responsetime='2' bonus='400' totalscore='500'></info>
//                        <info isright='true' responsetime='2' bonus='400' totalscore='500'></info>
//                        <info isright='true' responsetime='2' bonus='400' totalscore='500'></info>
//                        <info isright='true' responsetime='2' bonus='400' totalscore='500'></info>
//                        <info isright='true' responsetime='2' bonus='400' totalscore='500'></info>
//                        <info isright='true' responsetime='2' bonus='400' totalscore='500'></info>
//                        <info isright='true' responsetime='2' bonus='400' totalscore='500'></info>
//                        <info isright='true' responsetime='2' bonus='400' totalscore='500'></info>
//                        <info isright='true' responsetime='2' bonus='400' totalscore='500'></info>
//                        <info isright='true' responsetime='2' bonus='400' totalscore='500'></info>
//                        <info isright='true' responsetime='2' bonus='400' totalscore='500'></info>
//                        <info isright='true' responsetime='2' bonus='400' totalscore='500'></info>
//                        <info isright='true' responsetime='2' bonus='400' totalscore='500'></info>
//                      </infos>
//                      <totalscores>7000</totalscores>
//                      <totaltimes>48</totaltimes>
//                    </data>";

            //读取xml
            XElement doc = XElement.Parse(@strXML);
            List<TestRecord> result = new List<TestRecord>();
            
            var infoList = doc.Descendants("infos").FirstOrDefault().Descendants().ToList();
            if (infoList != null)
            {
                
                    TestRecord tr = new TestRecord();
                    
                        tr.UserId = Convert.ToInt32(doc.Descendants("userid").FirstOrDefault().Value);
                        tr.TestId = Convert.ToInt32(doc.Descendants("testid").FirstOrDefault().Value);                      
                        for (int i = 0; i < infoList.Count(); i++)
                        {
                            tr.Value += infoList[i].ToString();
                        }
                        tr.StepNo = Convert.ToInt32(doc.Descendants("totalscores").FirstOrDefault().Value);
                        tr.TotalTime = Convert.ToDouble(doc.Descendants("totaltimes").FirstOrDefault().Value);  
                    result.Add(tr);
                
            }
            return result;
            }

            
        
        #endregion
    }
}
